package cn.manyufun.myf.ui.news.activity;

import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import butterknife.BindView;
import butterknife.OnClick;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.ApiConstants;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxManager;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.common.commonutils.RequestBodyUtils;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonutils.UserInfoUtils;
import cn.manyufun.myf.common.share.UmShare;
import cn.manyufun.myf.common.webview.BaseWebView;
import cn.manyufun.myf.ui.comics.activity.ComicsDetailActivity;
import cn.manyufun.myf.ui.common.CommonListActivity;
import cn.manyufun.myf.ui.common.PhotosDetailActivity;
import cn.manyufun.myf.ui.user.activity.LoginAct;
import cn.manyufun.myf.widget.ObservableWebView;
import rx.functions.Action1;

import static cn.manyufun.myf.common.commonutils.RequestBodyUtils.getLikeRequestBody;
import static cn.manyufun.myf.widget.ObservableWebView.SCROLL_DISTANCE;

public class NewsDetailActivity extends BaseActivity {
    public static final String EXTRA_DATA_ARTICLE_ID = "article_id";
    public static final String EXTRA_DATA_ARTICLE_TITLE = "article_title";
    public static final String EXTRA_DATA_ARTICLE_IMG = "article_img";
    @BindView(R.id.app_bar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.webview)
    ObservableWebView mWebView;
    @BindView(R.id.et_comment)
    EditText mEtComment;
    @BindView(R.id.btn_submit)
    ImageView mBtnSubmit;
    private String newsURL;

    @OnClick(R.id.toolbar_ic_share)
    void share() {
        doShare();
    }

    private BaseWebView baseWebView;
    private long refrenceID;
    private String mTitle;
    private String mImg;

    private void doShare() {
        UmShare umShare = new UmShare(this, mTitle, newsURL, mImg);
        umShare.Share(new UmShare.UmShareShareInterface() {
            @Override
            public void shareCallback() {
                ToastUtil.showLong("分享成功！");
            }

            @Override
            public void onShareFailed(String result) {

                ToastUtil.showLong("分享失败," + result);
            }
        });
    }

    long mParentId = 0;

    @OnClick(R.id.btn_submit)
    void sendReply() {
        if (!UserInfoUtils.getInstance().checkLogin()) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
            LoginAct.startAction(NewsDetailActivity.this, bundle);
            return;
        }
        String content = mEtComment.getText().toString();

        if (TextUtils.isEmpty(content)) {
            ToastUtil.showLong("请输入评论内容！");
            return;
        }
        Api.getDefault(HostType.manyufun).setArticleReply(RequestBodyUtils.getArticleReplyRequestBody(refrenceID, content, mParentId))
                .compose(RxSchedulers.<BaseBean>io_main())
                .subscribe(new RxSubscriber<BaseBean>(this, false) {
                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    protected void _onNext(BaseBean posterBean) {
                        if (posterBean.getSuccess().equals("1")) {
                            ToastUtil.show("提交成功", 3);
                            mEtComment.clearFocus();
                            mEtComment.setText("");
                            mParentId = 0;
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(mEtComment.getWindowToken(), 0);
                            mWebView.reload();
                        } else {
                            ToastUtil.show(posterBean.getErrorMsg(), 3);
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    public static void startAction(Context context) {
        startAction(context, null);
    }

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, NewsDetailActivity.class);
        if (bundle != null)
            intent.putExtras(bundle);
        context.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    public void initPresenter() {
        new RxManager().on(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, new Action1<BaseBean>() {
            @Override
            public void call(BaseBean baseBean) {
                mEtComment.setHint(R.string.news_detail_comment_hint);
                mEtComment.setOnClickListener(null);
                mEtComment.setOnFocusChangeListener(null);
            }
        });
    }

    BaseWebView.JsApiCallback jsCallback = new BaseWebView.JsApiCallback() {
        @Override
        public void reply(long articleID, long replyID) {
            if (!UserInfoUtils.getInstance().checkLogin()) {
                Bundle bundle = new Bundle();
                bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
                LoginAct.startAction(NewsDetailActivity.this, bundle);
                return;
            }
            mParentId = replyID;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mEtComment.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            });
        }

        @Override
        public void favor(long articleID, long replyID) {
            if (!UserInfoUtils.getInstance().checkLogin()) {
                Bundle bundle = new Bundle();
                bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
                LoginAct.startAction(NewsDetailActivity.this, bundle);
                return;
            }
            Api.getDefault(HostType.manyufun).like(getLikeRequestBody(1, replyID))
                    .compose(RxSchedulers.<BaseBean>io_main())
                    .subscribe(new RxSubscriber<BaseBean>(NewsDetailActivity.this, false) {
                        @Override
                        public void onStart() {
                            super.onStart();
                        }

                        @Override
                        protected void _onNext(BaseBean posterBean) {
                            if (posterBean.getSuccess().equals("1")) {
                                showShortToast("点赞 + 1");
                            } else {

//                                            showShortToast(posterBean.getErrorMsg());
                                showShortToast("已点赞");
                            }

                        }

                        @Override
                        protected void _onError(String message) {
                            showShortToast(message);
                        }
                    });
        }

        @Override
        public void like(long articleID) {
            if (!UserInfoUtils.getInstance().checkLogin()) {
                Bundle bundle = new Bundle();
                bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
                LoginAct.startAction(NewsDetailActivity.this, bundle);
                return;
            }
            Api.getDefault(HostType.manyufun).like(getLikeRequestBody(1, articleID, 2))
                    .compose(RxSchedulers.<BaseBean>io_main())
                    .subscribe(new RxSubscriber<BaseBean>(NewsDetailActivity.this, false) {
                        @Override
                        public void onStart() {
                            super.onStart();
                        }

                        @Override
                        protected void _onNext(BaseBean posterBean) {
                            if (posterBean.getSuccess().equals("1")) {
                                showShortToast("点赞 + 1");
                            } else {

//                                            showShortToast(posterBean.getErrorMsg());
                                showShortToast("已点赞");
                            }

                        }

                        @Override
                        protected void _onError(String message) {
                            showShortToast(message);
                        }
                    });
        }

        @Override
        public void openCommonList(int type, long comicsId) {
            Bundle bundle = new Bundle();
            bundle.putInt(CommonListActivity.EXTRA_DATA_TYPE, type);
            bundle.putLong(CommonListActivity.EXTRA_DATA_OTHER, comicsId);
            CommonListActivity.startAction(NewsDetailActivity.this, bundle);
        }

        @Override
        public void openComicsDetail(long comicsId) {
            Bundle bundle = new Bundle();
            bundle.putLong(ComicsDetailActivity.FILTER, comicsId);
            ComicsDetailActivity.startAction(mContext, bundle);
        }

        @Override
        public void openImageDetail(String imgUrl) {
            PhotosDetailActivity.startAction(mContext, imgUrl);
        }
    };


    boolean showToolBar = false;
    @Override
    public void initView() {
        initToolBar();
        if (!UserInfoUtils.getInstance().checkLogin()) {
            mEtComment.setHint(R.string.news_detail_comment_hint_login);
            mEtComment.setOnClickListener((view -> {
                Bundle bundle = new Bundle();
                bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
                LoginAct.startAction(NewsDetailActivity.this, bundle);
            }));
            mEtComment.setOnFocusChangeListener((view, b) -> {
                if (b) {
                    Bundle bundle = new Bundle();
                    bundle.putString(LoginAct.LOGIN_FROM, NewsDetailActivity.class.getSimpleName());
                    LoginAct.startAction(NewsDetailActivity.this, bundle);
                }
            });
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mAppBarLayout.setOutlineProvider(null);
            StateListAnimator stateListAnimator = new StateListAnimator();
            stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(mAppBarLayout, "elevation", 0.1f));
            mAppBarLayout.setStateListAnimator(stateListAnimator);
        }
        refrenceID = getIntent().getLongExtra(EXTRA_DATA_ARTICLE_ID, 0);
        mTitle = getIntent().getStringExtra(EXTRA_DATA_ARTICLE_TITLE);
        mImg = getIntent().getStringExtra(EXTRA_DATA_ARTICLE_IMG);
        baseWebView = new BaseWebView(NewsDetailActivity.this, mWebView, jsCallback);
        mWebView.setOnScrollChangedCallback((x, y, dx, dy) -> {
            ColorDrawable[] color = {new ColorDrawable(Color.TRANSPARENT), new ColorDrawable(Color.WHITE)};
            TransitionDrawable trans = new TransitionDrawable(color);

            if (y > SCROLL_DISTANCE && !showToolBar) {
                showToolBar = true;
                LogUtils.logd("xwx+" + y);
//                mAppBarLayout.setBackground(getResources().getDrawable(R.color.white));
                mAppBarLayout.setBackground(trans);
                trans.startTransition(400);
                toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_18dp);
                toolbar.setTitle(mTitle);
                toolbar.setTitleTextColor(getResources().getColor(R.color.black));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mAppBarLayout.setOutlineProvider(null);
                    StateListAnimator stateListAnimator = new StateListAnimator();
                    stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(mAppBarLayout, "elevation", 4f));
                    mAppBarLayout.setStateListAnimator(stateListAnimator);
                }
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                    mFam.animate().alpha(0);
//                mAppBarLayout.animate().alpha(1)
//                        .setInterpolator(new AccelerateDecelerateInterpolator())
//                        .setListener(new Animator.AnimatorListener() {
//                            @Override
//                            public void onAnimationStart(Animator animation) {
//
//                            }
//
//                            @Override
//                            public void onAnimationEnd(Animator animation) {
//                                toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_18dp);
//                                toolbar.setTitle("####");
//                                toolbar.setTitleTextColor(getResources().getColor(R.color.black));
//                                mAppBarLayout.setBackgroundColor(getResources().getColor(R.color.white));
//                            }
//
//                            @Override
//                            public void onAnimationCancel(Animator animation) {
//
//                            }
//
//                            @Override
//                            public void onAnimationRepeat(Animator animation) {
//
//                            }
//                        });
            } else if (y < SCROLL_DISTANCE && showToolBar) {
                showToolBar = false;
                LogUtils.logd("xwx-" + y);
                mAppBarLayout.setBackgroundColor(getResources().getColor(R.color.transparent));
//                mAppBarLayout.setBackground(trans);
//                trans.reverseTransition(400);
                toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_white_18dp);
                toolbar.setTitle("");
                toolbar.setTitleTextColor(getResources().getColor(R.color.white));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mAppBarLayout.setOutlineProvider(null);
                    StateListAnimator stateListAnimator = new StateListAnimator();
                    stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(mAppBarLayout, "elevation", 0.1f));
                    mAppBarLayout.setStateListAnimator(stateListAnimator);
                }
                int flag = getWindow().getDecorView().getSystemUiVisibility()
                        & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                getWindow().getDecorView().setSystemUiVisibility(flag);
//                mAppBarLayout.animate().alpha(1)
//                        .setInterpolator(new AccelerateDecelerateInterpolator())
//                        .setListener(new Animator.AnimatorListener() {
//                            @Override
//                            public void onAnimationStart(Animator animation) {
//
//                            }
//
//                            @Override
//                            public void onAnimationEnd(Animator animation) {
//                                toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_white_18dp);
//                                toolbar.setTitle("");
//                            }
//
//                            @Override
//                            public void onAnimationCancel(Animator animation) {
//
//                            }
//
//                            @Override
//                            public void onAnimationRepeat(Animator animation) {
//
//                            }
//                        });
            }
        });

        newsURL = ApiConstants.H5_HOST + refrenceID + ApiConstants.h5_EXT;
        mWebView.loadUrl(newsURL);

    }

    private void initToolBar() {

        SetTranslanteBar();
//        WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
//        localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void onDestroy() {
        mWebView.removeJavascriptInterface("api");
        mWebView.removeAllViews();
        mWebView.destroy();

        super.onDestroy();
    }
}
